package com.ics.cmsadmin.modules.pub.service;

import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.enums.LevelEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.modules.basic.dao.CollectionDao;
import com.ics.cmsadmin.modules.pub.bean.PointVO;
import com.ics.cmsadmin.modules.pub.bean.Topic;
import com.ics.cmsadmin.modules.pub.bean.TopicDTO;
import com.ics.cmsadmin.modules.pub.bean.TopicVO;
import com.ics.cmsadmin.modules.pub.dao.TopicMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("TopicService")
public class TopicService extends ResourceService<TopicMapper, Topic, Integer> {

    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private PointService pointService;

    @Autowired
    private CollectionDao collectionDao;


    public TopicVO get(Integer id, String userId) {
        Topic topic = super.get(id);
        if (topic == null) {
            throw new CmsException(ApiResultEnum.TOPIC_NOT_EXIST);
        }
        return appendAttributes(topic, userId);
    }

    public List<TopicDTO> listDetail(Integer unitId, String userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("unitId", unitId);
        List<TopicDTO> topicDTOList = new ArrayList<>();
        List<Topic> topicList = topicMapper.selectAll(map);
        List<PointVO> pointList = pointService.getMultiple(map, userId);
        topicList.forEach(topic -> {
            TopicDTO topicDTO = new TopicDTO();
            TopicVO topicVO = appendAttributes(topic, userId);
            topicDTO.setTopic(topicVO);
            List<PointVO> topicPoints = new ArrayList<>();
            pointList.forEach(point -> {
                if (topic.getId().equals(point.getTopicId())) {
                    topicPoints.add(point);
                }
            });
            topicDTO.setPointList(topicPoints);
            topicDTOList.add(topicDTO);
        });
        return topicDTOList;
    }

    private TopicVO appendAttributes(Topic topic, String userId) {
        TopicVO topicVO = new TopicVO();
        BeanUtils.copyProperties(topic, topicVO);
        topicVO.setId(topic.getId());
        topicVO.setCollected(collectionDao.select(userId, LevelEnum.topic, String.valueOf(topic.getId())));

        return topicVO;
    }
}
